<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
    <script type='text/javascript' src='../vue.js'></script>
    
</head>
<body>
    
    <div id="root">
        <h2>人员列表</h2>
        <!-- <input type="text" placeholder="输入姓名" v-model="presonName" @keyup.enter.delete="search"> </input>  -->
        <input type="text" placeholder="输入姓名" v-model="presonName"> </input> 
        <br>
        <ul> 
            <li v-for="p in searchPresons2">{{p.name}} - {{p.age}}</li>
        </ul>
        <button @click="sortType = 0">年龄默认排序序</button>
        <button @click="sortType = 1">年龄升序</button>
        <button @click="sortType = 2">年龄降序</button>
        
    </div>


    <script type='text/javascript'>
        new Vue({ 
            el: '#root',
            data: {
                presonName:'',
                sortType:0,
                presons:[
                    {name: '马冬梅',age: 18,id: 1},
                    {name: '周冬雨',age: 12,id: 2},
                    {name: '周杰伦',age: 14,id: 3},
                    {name: '温兆伦',age: 13,id: 4}
                ],
                searchPresons:[]
                
            },
            computed:{
                searchPresons2(){
                    let arr = this.presons.filter((p)=>{
                        return p.name.includes(this.presonName) 
                    })
                    if(this.sortType == 0){
                        return arr
                    }else{
                        return arr.sort((v1,v2)=>{
                           return this.sortType === 1 ? v1.age - v2.age : v2.age - v1.age
                        })
                    }
                }
            },
            methods: {
                sortArr: function(){
                    let arr = this.presons.filter((p)=>{
                        return p.name.includes(this.presonName)
                    })
                    if(this.sortType == 0){
                        this.searchPresons = arr
                    }else{
                        this.searchPresons= arr.sort((p1,p2)=>{
                            return this.sortType == 1 ? p1.age - p2.age : p2.age - p1.age
                        })
                    }

                }
            },
            watch:{
                presonName: {
                    deep:true,
                    immediate:true,
                    handler(newVal){
                        this.sortArr()
                    }
                },
                sortType(){
                    console.log(this.sortType)
                    this.sortArr()
                }

            }
        })
    </script>
    
    
    
</body>
</html>